package com.example.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.example.config.OSSConfig;
import com.example.service.FileService;
import com.example.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author yinxin
 * @version 1.0
 * @Description:
 * @date 2022/6/710:00
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {


    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadUserImg(MultipartFile file) {
        String bucketname = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //客户端oss构建
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();

        //日期名作为文件夹
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String folder = formatter.format(now);
        String fileName = CommonUtil.generateUUID();
        String extensible = originalFilename.substring(originalFilename.lastIndexOf("."));

        //在oss上的bucket创建文件夹
        String newFileDir = "user/" + folder + "/" + fileName + extensible;

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketname, newFileDir, file.getInputStream());
            //拼装返回路径
            if(putObjectResult!=null){
                return "https://" + bucketname + "." + endpoint + "/" + newFileDir;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            ossClient.shutdown();
        }
        return null;
    }
}
